
package com.yimixian.app.cart;

import android.animation.Animator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.PlusMinusIconMessage;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.adapter.CouDanResultAdapter;
import com.yimixian.app.adapter.SearchResultAdapter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.UMengConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.HotTips;
import com.yimixian.app.model.SortGoodsItem;
import com.yimixian.app.rest.api.CartUpdateAPI;
import com.yimixian.app.rest.api.CouDanKeyAPI;
import com.yimixian.app.rest.api.HotTipsAPI;
import com.yimixian.app.ui.BaseHttpFragment;
import com.yimixian.app.ui.FlowLayout;
import com.yimixian.app.ui.ParabolaView;
import com.yimixian.app.ui.PlusMinusIcon;
import com.yimixian.app.user.UserRegistrationActivity;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.PaoWuXianAnimTool;
import com.yimixian.app.util.PaoWuXianAnimator;
import com.yimixian.app.util.ServiceUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.animator.animatorUtils;
import com.ymx.sdk.widget.ListViewLoadMore.AutoLoadMoreListView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.greenrobot.event.EventBus;
import retrofit.client.Response;

/**
 * Created by szy on 2016/1/18.
 */
public class CouDanFragment extends BaseHttpFragment
        implements GoodsItemPresenter.OnPlusButtonClickListener,
        AutoLoadMoreListView.OnLoadMoreListener, View.OnClickListener,
        ServiceUtils.CountDownDataListener {
    @InjectView(R.id.search_tips_history_container)
    RelativeLayout mSearchTipsHistoryContainer;
    @InjectView(R.id.search_content_container)
    RelativeLayout mSearchContentContainer;
    @InjectView(R.id.search_tips_container)
    RelativeLayout mSearchTipsContainer;
    @InjectView(R.id.search_history_container)
    LinearLayout mSearchHistoryContainer;
    @InjectView(R.id.clear_search_history)
    TextView mClearSearchHistoryTv;
    @InjectView(R.id.flowlayout_container)
    FlowLayout mFlowLayoutContainer;
    @InjectView(R.id.search_history_title)
    TextView mSearchHistoryTitle;
    @InjectView(R.id.auto_loadmore_listview)
    AutoLoadMoreListView mAutoLoadMoreListView;
    @InjectView(R.id.iv_detail_cart)
    ImageView mCartDetailView;
    @InjectView(R.id.cart_detail_contnent)
    public TextView mCartDetailContent;
    @InjectView(R.id.fl_detail_cart)
    FrameLayout mCartView;
    @InjectView(R.id.iv_detail_cart_hide)
    ImageView mDetailCartHide;
    @InjectView(R.id.hot_tips_title)
    TextView mHotTipsTitle;
    @InjectView(R.id.ll_no_data)
    LinearLayout mLlNoData;

    private HotTipsAPI mHotTipsAPI;
    private CouDanKeyAPI couDanAPI;
    private String mSearchKey = "";
    private CouDanResultAdapter mCouDanResultAdapter;
    private Handler mHandler = new Handler();
    private boolean mIsMore = false;
    private int mNextPage = 0;
    private List<SortGoodsItem> mSortGoodsItems;
    private CartUpdateAPI mCartUpdateAPI;
    private PlusMinusIcon mPlusMinusIcon;
    private View mHeaderWithoutView;
    private boolean mIsFirstAdd = true;
    private View mFooterView;

    public static int FROM_COU_DAN = 1001;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                UMengConstants.NEW_ADDON_PV);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().registerSticky(this);
        }
        View view = inflater.inflate(R.layout.fragment_search, null);
        ButterKnife.inject(this, view);
        if (YMXMainActivity.IS_FIRST_GET_HOT_TIPS) {
            fetchData(true, HotTipsAPI.GET_HOT_TIPS);
            YMXMainActivity.IS_FIRST_GET_HOT_TIPS = false;
        }
        initView();
        initSearchHistoryView();
        return view;
    }

    public void initView() {
        mSortGoodsItems = new ArrayList<>();
        mAutoLoadMoreListView.setOnLoadMoreListener(this);
        mClearSearchHistoryTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> list = new ArrayList<>();
                SharedPreferencesHelper.saveSearchHistory(list);
                initSearchHistoryView();
            }
        });
        mCartDetailView.setOnClickListener(this);
        List<String> hotTipsList = SharedPreferencesHelper.getHotTips();
        if (hotTipsList != null) {
            initHotTipsView(hotTipsList);
        }
        mFooterView = View.inflate(getActivity(), R.layout.search_footer_view, null);
        mFooterView.setVisibility(View.GONE);
        mFooterView.setEnabled(false);
        CartManager.getInstance().setCartQuantityTextView(mCartDetailContent);
        mFlowLayoutContainer.setVisibility(View.GONE);
    }

    private void addFooterView() {
        View loadMoreView = mAutoLoadMoreListView.getLoadMoreFooterView();
        if (loadMoreView != null) {
            mAutoLoadMoreListView.removeFooterView(loadMoreView);
        }
        if (mFooterView != null) {
            mAutoLoadMoreListView.addFooterView(mFooterView);
        }
        if (loadMoreView != null) {
            mAutoLoadMoreListView.addFooterView(loadMoreView);
        }
    }

    private void removeFooterView() {
        if (mFooterView != null) {
            mAutoLoadMoreListView.removeFooterView(mFooterView);
        }
    }

    public void initSearchHistoryView() {

        if (mSearchHistoryContainer != null && mClearSearchHistoryTv != null
                && mSearchHistoryTitle != null) {
            mSearchHistoryContainer.removeAllViews();
            ArrayList<String> histories = SharedPreferencesHelper.getSearchHistory();
            if (histories == null || histories.size() < 1) {
                mSearchHistoryContainer.setVisibility(View.GONE);
                mClearSearchHistoryTv.setVisibility(View.GONE);
                mSearchHistoryTitle.setVisibility(View.GONE);
            } else {
                mSearchHistoryContainer.setVisibility(View.VISIBLE);
                for (final String s : histories) {
                    if (isAdded() && !TextUtils.isEmpty(s)) {
                        View view = View.inflate(getActivity(), R.layout.text_view_history, null);
                        RelativeLayout rlContainer = (RelativeLayout) view
                                .findViewById(R.id.rl_container);
                        TextView textView = (TextView) view.findViewById(R.id.text);
                        textView.setText(s);
                        textView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (isAdded() && getActivity() instanceof CouDanActivity) {
                                    ((CouDanActivity) getActivity()).setSearchViewText(s);
                                    ((CouDanActivity) getActivity()).notifyHistoryList(s);
                                }
                            }
                        });
                        ((RelativeLayout) rlContainer.getParent()).removeView(rlContainer);
                        mSearchHistoryContainer.addView(rlContainer);
                    }
                }
                mClearSearchHistoryTv.setVisibility(View.VISIBLE);
                mSearchHistoryTitle.setVisibility(View.VISIBLE);
            }
        }
    }

    private void hideFooterView() {
        if (mFooterView != null) {
            mFooterView.setVisibility(View.GONE);
        }
    }

    private void showFooterView() {
        if (mFooterView != null) {
            mFooterView.setVisibility(View.VISIBLE);
        }
    }

    public void initWithoutView(boolean isShow) {
        if (mHeaderWithoutView == null && isAdded()) {
            mHeaderWithoutView = View.inflate(getActivity(), R.layout.search_without_result_view,
                    null);
        }
        if (isShow) {
            if (mAutoLoadMoreListView != null) {
                mLlNoData.setVisibility(View.VISIBLE);
                mAutoLoadMoreListView.setVisibility(View.GONE);
                mCartView.setVisibility(View.GONE);
            }
        } else {
            if (mAutoLoadMoreListView != null) {
                mAutoLoadMoreListView.removeHeaderView(mHeaderWithoutView);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        updateCartDetailText();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.reset(this);
    }

    private void updateCartDetailText() {
        if (isAdded() && CartManager.getInstance().isUserLogin()) {
            UiUtils.updateCartDescription(getActivity(), Constants.PageType.SEARCH);
        }
    }

    public void startSearch(String searchText) {
        removeFooterView();
        if (isAdded() && getActivity() instanceof CouDanActivity) {
            ((CouDanActivity) getActivity()).mIsStartSearch = true;
        }
        UiUtils.closeSoftKeyBoard(getActivity());
        mSearchTipsHistoryContainer.setVisibility(View.GONE);
        mSearchContentContainer.setVisibility(View.VISIBLE);
        mAutoLoadMoreListView.setVisibility(View.VISIBLE);
        showCartViewByAnimation();
        mSearchKey = searchText;
        if (mCouDanResultAdapter != null) {
            mCouDanResultAdapter.clearList();
        }
        if (mAutoLoadMoreListView != null && mHeaderWithoutView != null) {
            mAutoLoadMoreListView.removeHeaderView(mHeaderWithoutView);
        }
        mNextPage = 0;
        showDialog("加载中", false);
        fetchData(true, CouDanKeyAPI.COU_DAN_KEY);
//        fetchData(true, SearchKeyAPI.SEARCH_KEY);
        CartManager.getInstance().setCartPriceData(mCartDetailContent);
    }

    private void showCartViewByAnimation() {
        mCartView.setAlpha(0.0f);
        mCartView.setVisibility(View.VISIBLE);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Animator animator = animatorUtils.translateY(mCartView,
                        mCartView.getMeasuredHeight(), 0, 400, new LinearInterpolator());
                animator.addListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) {
                        mCartView.setAlpha(1.0f);
                    }

                    @Override
                    public void onAnimationEnd(Animator animation) {
                    }

                    @Override
                    public void onAnimationCancel(Animator animation) {
                    }

                    @Override
                    public void onAnimationRepeat(Animator animation) {
                    }
                });
                animator.start();
            }
        }, 10);
    }

    public void showTips() {
        if (mSearchContentContainer != null && mSearchTipsHistoryContainer != null) {
            initSearchHistoryView();
            mSearchContentContainer.setVisibility(View.GONE);
            mSearchTipsHistoryContainer.setVisibility(View.VISIBLE);
            mLlNoData.setVisibility(View.GONE);
        }
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        if (HotTipsAPI.GET_HOT_TIPS.equals(requestKeys)) {
            mHotTipsAPI = new HotTipsAPI(this);
            mHotTipsAPI.getHotTips();
        } else if (CouDanKeyAPI.COU_DAN_KEY.equals(requestKeys)) {
            couDanAPI = new CouDanKeyAPI(this);
            if (!TextUtils.isEmpty(mSearchKey)) {
                Intent intent = getActivity().getIntent();
                String pici = intent.getStringExtra("pici");
                String group_id = intent.getStringExtra("group_id");
                couDanAPI.getCouDanData(pici, group_id);
            }
        } else if (requestKeys != null && CartUpdateAPI.CART_UPDATE_API.equals(requestKeys)) {
            if (mCartUpdateAPI == null) {
                mCartUpdateAPI = new CartUpdateAPI(this);
            }
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if (url.contains(HotTipsAPI.GET_HOT_TIPS)) {
            HotTips hotTips = mHotTipsAPI.parseJson(responseJson);
            if (hotTips != null && hotTips.hotTips != null
                    && hotTips.hotTips instanceof ArrayList) {
                ArrayList<String> hottips = (ArrayList) hotTips.hotTips;
                SharedPreferencesHelper.saveHotTips(hottips);
                initHotTipsView(hotTips.hotTips);
            }
        } else if (url.contains(CouDanKeyAPI.COU_DAN_KEY)) {
//            SearchKeyResult searchKeyResult = mSearchKeyAPI.parseJson(responseJson);
            List<GoodsItem> result = couDanAPI.parseJson(responseJson);
            if (result != null) {
                if (result.size() > 0) {
                    // 有搜索到的结果
                    initWithoutView(false);
                    if (couDanAPI == null) {
                        couDanAPI = new CouDanKeyAPI(this);
                    }
                    List<SortGoodsItem> sortGoodsItem = couDanAPI.translateArray(result);
                    if (mSortGoodsItems != null) {
                        mSortGoodsItems.addAll(sortGoodsItem);
                    }
                    notifyDataSet();
                }
//                else if (searchKeyResult.hotGoods != null) {
//                    // 没有搜索结果 显示热门商品
//                    initWithoutView(true);
//                    mIsMore = false;
//                    mNextPage = 0;
//                    if (searchKeyResult.hotGoods.size() > 0) {
//                        if (mSearchKeyAPI == null) {
//                            mSearchKeyAPI = new SearchKeyAPI(this);
//                        }
//                        List<SortGoodsItem> sortGoodsItem = mSearchKeyAPI
//                                .translateArray(searchKeyResult.hotGoods);
//                        if (mSortGoodsItems != null) {
//                            mSortGoodsItems.addAll(sortGoodsItem);
//                        }
//                        notifyDataSet();
//                    }
//                }
                updateCartDetailText();
                hideDialog();
            }
        } else if (mCartUpdateAPI != null) {
            if (url.contains(mCartUpdateAPI.CART_UPDATE)) {
                CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
                CartManager.getInstance().updateCartGoods(cartUpdate, mPlusMinusIcon);
            }
            if (mPlusMinusIcon != null) {
                mPlusMinusIcon.setButtonCanClick(true);
            }
            updateCartDetailText();
            if (mIsFirstAdd) {
                if (isAdded()) {
                    UiUtils.closeSoftKeyBoard(getActivity());
                    mIsFirstAdd = false;
                }
            }
        }
        hidePopupWindow();
        hideDialog();
    }

    @Override
    public void getRawResponse(String url, Response response) {
        super.getRawResponse(url, response);
        ServiceUtils.setTime(response);
    }

    private void notifyDataSet() {
        if (mIsMore) {
            hideFooterView();
        } else {
            addFooterView();
            showFooterView();
        }

        if (mSortGoodsItems != null && mSortGoodsItems.size() > 0) {
            List<GoodsItem> goodsItems = new ArrayList<>();
            for (SortGoodsItem sortGoodsItem : mSortGoodsItems) {
                if (sortGoodsItem.leftGoodsItem != null)
                    goodsItems.add(sortGoodsItem.leftGoodsItem);
                if (sortGoodsItem.RightGoodsItem != null)
                    goodsItems.add(sortGoodsItem.RightGoodsItem);
            }
            ServiceUtils.infilterServiceData(getActivity(), goodsItems,
                    Constants.ServicePageType.SEARCHFRAGMENT);
        }

        if (mCouDanResultAdapter == null) {
            if (isAdded() && mAutoLoadMoreListView != null) {
                mCouDanResultAdapter = new CouDanResultAdapter(getActivity(), mSortGoodsItems,
                        this);
                mAutoLoadMoreListView.setAdapter(mCouDanResultAdapter);
            }
        } else {
            mCouDanResultAdapter.setList(mSortGoodsItems);
        }
        mCouDanResultAdapter.setIsFromCouDanPage(true);
        if (mAutoLoadMoreListView != null) {
            mAutoLoadMoreListView.onLoadMoreComplete();
        }
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        if (mPlusMinusIcon != null) {
            mPlusMinusIcon.setButtonCanClick(true);
        }
        hidePopupWindow();
        hideDialog();
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
    }

    private void initHotTipsView(List<String> hotTips) {
        if (isAdded() && mFlowLayoutContainer != null) {
            mFlowLayoutContainer.removeAllViews();
            mFlowLayoutContainer.initChild(getActivity(), hotTips);
        }
    }

    @Override
    public void onPlusButtonClick(View plusView, Point point, Bitmap animBack) {

        PaoWuXianAnimTool.startAnim(getActivity(), plusView, mDetailCartHide, animBack, PaoWuXianAnimTool.DEFAULT_DURATION, new PaoWuXianAnimator.onPaoWuXianEndListener() {
            @Override
            public void onEnd() {
                UiUtils.showScaleAnimation(mDetailCartHide);
            }
        });

        if(true)
            return;

        ParabolaView parabolaView = new ParabolaView(getActivity(), animBack);
        if (isAdded() && getActivity() instanceof CouDanActivity) {
            CouDanActivity couDanActivity = (CouDanActivity) getActivity();
            if (couDanActivity != null && couDanActivity.mAnimattionContainer != null) {
                couDanActivity.mAnimattionContainer.addView(parabolaView);
            }
        }
        parabolaView.setAnimListener(new ParabolaView.AnimListener() {
            @Override
            public void onEndAnim() {
                UiUtils.showScaleAnimation(mDetailCartHide);
            }
        });
        parabolaView.startAnimation(mHandler, SharedPreferencesHelper.getCartViewLocation(), point);
    }

    @Override
    public void onLoadMore() {
        if (checkNetWorkState()) {
            if (mIsMore) {
                fetchData(true, CouDanKeyAPI.COU_DAN_KEY);
            } else {
                mAutoLoadMoreListView.onLoadMoreComplete();
            }
        } else {
            mAutoLoadMoreListView.onLoadMoreComplete();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_detail_cart:
                if (userLogin())
                    return;
                if (isAdded()) {
                    MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                            UMengConstants.NEW_SEARCH_CARTBTN);
                    if(getActivity() instanceof CouDanActivity){
                        getActivity().finish();
                    }else{
                        DateUtil.setCityUMeng(null, UMengConstants.NEW_BOTTOM_CARTBTN);
                        MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
                                UMengConstants.NEW_ADDON_CARTBTN);
                        startActivity(CartDetailActivity.buildIntent(getActivity()));
                    }
                }
                break;
        }
    }

    private boolean userLogin() {
        if (DataManager.getInstance().get(CacheKeys.TOKEN) == null && isAdded()) {
            Intent intent = new Intent(getActivity(), UserRegistrationActivity.class);
            getActivity().startActivityForResult(intent, Constants.CART_REGIST_REQUEST_CODE);
            return true;
        }
        return false;
    }

    // 刷新ListView中的数据
    public void onEventMainThread(String message) {
        if (message != null) {
            // 刷新HomeFragment中商品列表
            if ((Constants.EVENT_BUS_HOME_FRAGMENT_REFRESH).equals(message)) {
                if (mCouDanResultAdapter != null) {
                    mCouDanResultAdapter.notifyDataSetChanged();
                    updateCartDetailText();
                }
                EventBus.getDefault().removeStickyEvent(message);
            }
            // 取消掉Loading框
            else if (Constants.EVENT_BUS_DISSMISS_DIALOG.equals(message)) {
                hidePopupWindow();
                if (mPlusMinusIcon != null) {
                    mPlusMinusIcon.setButtonCanClick(true);
                }
                EventBus.getDefault().removeStickyEvent(message);
            }
        }
    }

    // 发起商品 + / - 的请求
    public void onEventMainThread(PlusMinusIconMessage message) {
        if (message != null) {
            if (Constants.STATE_COUDANFRAGMENT_BUTTON_BROADCAST.equals(message.message)
                    || (Constants.STATE_COUDANFRAGMENT_BUTTON_BROADCAST + "/IsFisrt")
                            .equals(message.message)) {
                mPlusMinusIcon = message.icon;
                if (isAdded()) {
                    showPopupWindow(getActivity(), R.id.popupwindow_container);
                }
                fetchData(true, CartUpdateAPI.CART_UPDATE_API);
                if (mPlusMinusIcon != null && mCartUpdateAPI != null) {
                    mCartUpdateAPI.mGoodId = mPlusMinusIcon.mGoodsItem.id;
                    if (Constants.PLUS_BUTTON_CLICKED_BROADCAST
                            .equals(mPlusMinusIcon.mButtonState)) {
                        dealPlusOrMinus(true);
                    } else if (Constants.MINUS_BUTTON_CLICKED_BROADCAST
                            .equals(mPlusMinusIcon.mButtonState)) {
                        dealPlusOrMinus(false);
                    }
                }
                EventBus.getDefault().removeStickyEvent(message);
            }
        }
    }

    // 处理未登录时的购物车商品加减
    private void dealPlusOrMinus(boolean isAdd) {
        if (CartManager.getInstance().isUserLogin()) {
            mCartUpdateAPI.mTrend = isAdd ? 1 : 0;
            mCartUpdateAPI.getCartUpdate();
        } else {
            try {
                if (isAdd) {
                    CartManager.getInstance().saveUnLoginCartData(mPlusMinusIcon.mGoodsItem.id,
                            true, mPlusMinusIcon);
                } else {
                    CartManager.getInstance().saveUnLoginCartData(mPlusMinusIcon.mGoodsItem.id,
                            false, mPlusMinusIcon);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            hidePopupWindow();
        }
    }

    // 地址管理页面 监听到地址改变更新首页内容
    public void onEventMainThread(ShowAdSelectChange event) {
        startSearch(mSearchKey);
        EventBus.getDefault().removeStickyEvent(event);
    }

    @Override
    public void isNeedUpdate() {
        if (mCouDanResultAdapter != null)
            mCouDanResultAdapter.notifyDataSetChanged();
    }

    @Override
    public void isNeedUnbindService() {

    }
}
